<template>
  <view class="container">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 顶部导航栏 -->
    <view class="top-nav">
      <view class="nav-left" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <view class="nav-center">
        <text class="nav-title">修改密码</text>
      </view>
      <view class="nav-right"></view>
    </view>
    
    <!-- 内容区域 -->
    <view class="content">
      <!-- 提示信息 -->
      <view class="tips">
        <text class="tips-icon">🔐</text>
        <text class="tips-text">为了您的账号安全，请定期修改密码</text>
      </view>
      
      <!-- 表单 -->
      <view class="form">
        <!-- 旧密码 -->
        <view class="form-item">
          <text class="label">当前密码</text>
          <view class="input-wrapper">
            <input 
              class="input" 
              :type="showOldPassword ? 'text' : 'password'"
              v-model="formData.oldPassword"
              placeholder="请输入当前密码"
              @input="clearError('oldPassword')"
            />
            <text class="eye-icon" @click="showOldPassword = !showOldPassword">
              {{ showOldPassword ? '👁️' : '👁️‍🗨️' }}
            </text>
          </view>
          <text class="error-text" v-if="errors.oldPassword">{{ errors.oldPassword }}</text>
        </view>
        
        <!-- 新密码 -->
        <view class="form-item">
          <text class="label">新密码</text>
          <view class="input-wrapper">
            <input 
              class="input" 
              :type="showNewPassword ? 'text' : 'password'"
              v-model="formData.newPassword"
              placeholder="请输入新密码（6-20位）"
              @input="validateNewPassword"
            />
            <text class="eye-icon" @click="showNewPassword = !showNewPassword">
              {{ showNewPassword ? '👁️' : '👁️‍🗨️' }}
            </text>
          </view>
          <text class="error-text" v-if="errors.newPassword">{{ errors.newPassword }}</text>
          
          <!-- 密码强度提示 -->
          <view class="password-strength" v-if="formData.newPassword">
            <text class="strength-label">密码强度：</text>
            <view class="strength-bar">
              <view 
                class="strength-item" 
                :class="{ 'active': passwordStrength >= 1, 'weak': passwordStrength === 1 }"
              ></view>
              <view 
                class="strength-item" 
                :class="{ 'active': passwordStrength >= 2, 'medium': passwordStrength === 2 }"
              ></view>
              <view 
                class="strength-item" 
                :class="{ 'active': passwordStrength >= 3, 'strong': passwordStrength === 3 }"
              ></view>
            </view>
            <text class="strength-text" :class="'strength-' + passwordStrength">
              {{ strengthText }}
            </text>
          </view>
        </view>
        
        <!-- 确认新密码 -->
        <view class="form-item">
          <text class="label">确认新密码</text>
          <view class="input-wrapper">
            <input 
              class="input" 
              :type="showConfirmPassword ? 'text' : 'password'"
              v-model="formData.confirmPassword"
              placeholder="请再次输入新密码"
              @input="validateConfirmPassword"
            />
            <text class="eye-icon" @click="showConfirmPassword = !showConfirmPassword">
              {{ showConfirmPassword ? '👁️' : '👁️‍🗨️' }}
            </text>
          </view>
          <text class="error-text" v-if="errors.confirmPassword">{{ errors.confirmPassword }}</text>
        </view>
      </view>
      
      <!-- 安全提示 -->
      <view class="security-tips">
        <text class="security-title">密码安全建议：</text>
        <text class="security-item">• 密码长度至少6位</text>
        <text class="security-item">• 建议包含数字、字母和特殊字符</text>
        <text class="security-item">• 不要使用生日、手机号等容易被猜到的密码</text>
      </view>
      
      <!-- 提交按钮 -->
      <button 
        class="submit-btn"
        :disabled="!isFormValid || loading"
        @click="handleSubmit"
      >
        {{ loading ? '修改中...' : '确认修改' }}
      </button>
    </view>
  </view>
</template>

<script>
import authService from '../../services/auth.js'
import { backToProfile } from '../../utils/navigation.js'

export default {
  data() {
    return {
      statusBarHeight: 0,
      showOldPassword: false,
      showNewPassword: false,
      showConfirmPassword: false,
      loading: false,
      formData: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      errors: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
    }
  },
  
  computed: {
    // 密码强度（1-弱，2-中，3-强）
    passwordStrength() {
      const pwd = this.formData.newPassword
      if (!pwd) return 0
      
      let strength = 0
      if (pwd.length >= 6) strength++
      if (pwd.length >= 10) strength++
      if (/[a-zA-Z]/.test(pwd) && /\d/.test(pwd)) strength++
      if (/[^a-zA-Z0-9]/.test(pwd)) strength++
      
      return Math.min(strength, 3)
    },
    
    strengthText() {
      const texts = ['', '弱', '中', '强']
      return texts[this.passwordStrength]
    },
    
    isFormValid() {
      return this.formData.oldPassword && 
             this.formData.newPassword && 
             this.formData.confirmPassword &&
             !this.errors.oldPassword &&
             !this.errors.newPassword &&
             !this.errors.confirmPassword
    }
  },
  
  onLoad() {
    this.getStatusBarHeight()
  },
  
  methods: {
    getStatusBarHeight() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 20
      document.documentElement.style.setProperty('--status-bar-height', this.statusBarHeight + 'px')
    },
    
    goBack() {
      backToProfile()
    },
    
    clearError(field) {
      this.errors[field] = ''
    },
    
    validateNewPassword() {
      this.clearError('newPassword')
      const pwd = this.formData.newPassword
      
      if (!pwd) {
        this.errors.newPassword = '请输入新密码'
        return false
      }
      
      if (pwd.length < 6) {
        this.errors.newPassword = '密码至少6位'
        return false
      }
      
      if (pwd.length > 20) {
        this.errors.newPassword = '密码最多20位'
        return false
      }
      
      if (pwd === this.formData.oldPassword) {
        this.errors.newPassword = '新密码不能与旧密码相同'
        return false
      }
      
      // 重新验证确认密码
      if (this.formData.confirmPassword) {
        this.validateConfirmPassword()
      }
      
      return true
    },
    
    validateConfirmPassword() {
      this.clearError('confirmPassword')
      const confirm = this.formData.confirmPassword
      
      if (!confirm) {
        this.errors.confirmPassword = '请确认新密码'
        return false
      }
      
      if (confirm !== this.formData.newPassword) {
        this.errors.confirmPassword = '两次输入的密码不一致'
        return false
      }
      
      return true
    },
    
    async handleSubmit() {
      // 验证所有字段
      if (!this.formData.oldPassword) {
        this.errors.oldPassword = '请输入当前密码'
        return
      }
      
      if (!this.validateNewPassword()) return
      if (!this.validateConfirmPassword()) return
      
      this.loading = true
      
      try {
        console.log('开始修改密码')
        
        const response = await authService.changePassword({
          oldPassword: this.formData.oldPassword,
          newPassword: this.formData.newPassword
        })
        
        console.log('修改密码成功:', response)
        
        uni.showToast({
          title: '密码修改成功',
          icon: 'success',
          duration: 1500
        })
        
        // 1.5秒后返回个人中心
        setTimeout(() => {
          backToProfile()
        }, 1500)
        
      } catch (error) {
        console.error('修改密码失败:', error)
        
        // 根据错误类型显示不同提示
        let errorMsg = '修改失败，请稍后重试'
        
        if (error.message && error.message.includes('旧密码')) {
          errorMsg = '当前密码不正确'
          this.errors.oldPassword = errorMsg
        } else if (error.message) {
          errorMsg = error.message
        }
        
        uni.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: #f5f5f5;
}

.status-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #fff;
  z-index: 1000;
}

.top-nav {
  position: fixed;
  top: var(--status-bar-height);
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  background: #fff;
  padding: 0 30rpx;
  border-bottom: 1rpx solid #eee;
  z-index: 999;
  
  .nav-left {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .back-icon {
      font-size: 36rpx;
      color: #333;
      font-weight: bold;
    }
  }
  
  .nav-center {
    flex: 1;
    text-align: center;
    
    .nav-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
  }
  
  .nav-right {
    width: 60rpx;
  }
}

.content {
  margin-top: calc(var(--status-bar-height) + 88rpx + 20rpx);
  padding: 0 30rpx 40rpx;
}

.tips {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
  
  .tips-icon {
    font-size: 40rpx;
  }
  
  .tips-text {
    flex: 1;
    font-size: 28rpx;
    color: #fff;
    line-height: 1.5;
  }
}

.form {
  background: #fff;
  border-radius: 16rpx;
  padding: 40rpx 30rpx;
  margin-bottom: 30rpx;
  
  .form-item {
    margin-bottom: 40rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .label {
      display: block;
      font-size: 28rpx;
      color: #333;
      font-weight: 600;
      margin-bottom: 20rpx;
    }
    
    .input-wrapper {
      position: relative;
      display: flex;
      align-items: center;
      background: #f8f8f8;
      border-radius: 12rpx;
      padding: 0 30rpx;
      height: 88rpx;
      
      .input {
        flex: 1;
        font-size: 28rpx;
        color: #333;
      }
      
      .eye-icon {
        font-size: 32rpx;
        cursor: pointer;
        padding: 10rpx;
      }
    }
    
    .error-text {
      display: block;
      font-size: 24rpx;
      color: #ff4757;
      margin-top: 10rpx;
      padding-left: 10rpx;
    }
  }
}

.password-strength {
  margin-top: 20rpx;
  display: flex;
  align-items: center;
  gap: 15rpx;
  
  .strength-label {
    font-size: 24rpx;
    color: #666;
  }
  
  .strength-bar {
    flex: 1;
    display: flex;
    gap: 8rpx;
    
    .strength-item {
      flex: 1;
      height: 8rpx;
      background: #e0e0e0;
      border-radius: 4rpx;
      transition: all 0.3s ease;
      
      &.active.weak {
        background: #ff4757;
      }
      
      &.active.medium {
        background: #ffa502;
      }
      
      &.active.strong {
        background: #26de81;
      }
    }
  }
  
  .strength-text {
    font-size: 24rpx;
    font-weight: 600;
    
    &.strength-1 {
      color: #ff4757;
    }
    
    &.strength-2 {
      color: #ffa502;
    }
    
    &.strength-3 {
      color: #26de81;
    }
  }
}

.security-tips {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 40rpx;
  
  .security-title {
    display: block;
    font-size: 28rpx;
    color: #333;
    font-weight: 600;
    margin-bottom: 20rpx;
  }
  
  .security-item {
    display: block;
    font-size: 26rpx;
    color: #666;
    line-height: 2;
  }
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: 600;
  border: none;
  
  &:disabled {
    opacity: 0.6;
  }
  
  &::after {
    border: none;
  }
}
</style>


